const api = require('../../utils/api.js');
const app = getApp();

Page({
  data: {
    load_more_count: 0,
    last_load_more_time: 0,
    is_loading: false,
    loading_class: '',
    cat_id: false,
    keyword: false,
    page: 1,
    limit: 20,
    goods_list: [],
    show_history: true,
    show_result: false,
    autofocus: false,
    history_list: [],
    currVal: '',
    isEmpty: true,
    theme: app.themeData,
    abnorData: {
      imgSrc: app.imgUrl + 'goods_empty.png',
      text: '未搜到相关的信息',
    },
    unit: '',
    isSelect: '0',
    animationData: {},
    flag: -1,
    showAssociate: false,
    isloading: false,
    imgUrl: app.imgUrl,
  },

  onShow() {
    let page = this;
    page.setData({
      history_list: page.getHistoryList(true),
    });
  },

  onLoad(options) {
    let that = this;
    let keyword = options && decodeURIComponent(options.keyword);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    app.pageOnLoad(this);
    if (keyword && keyword !== 'undefined') {
      this.setData({
        keyword,
        currVal: keyword,
      });
      this.searchSure();
    } else {
      this.setData({
        autofocus: true,
      });
    }
    this.loadHotSearchList();
  },

  clearTxt() {
    this.setData({
      currVal: '',
      isEmpty: true,
      goods_list: [],
      showAssociate: false,
    });
  },

  chooseSearch(e) {
    let { value } = e.currentTarget.dataset;
    this.setData({
      showAssociate: false,
      currVal: value,
    });
  },

  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      currVal: e.detail.value,
      showAssociate: true,
    });
  },

  inputFocus() {
    this.setData({
      show_history: true,
      show_result: false,
    });
  },

  inputBlur() {
    let that = this;
    if (that.data.goods_list.length > 0) {
      setTimeout(() => {
        that.setData({
          show_history: false,
          show_result: true,
        });
      }, 300);
    }
  },

  inputConfirm(e) {
    let keyword = e.detail.value.trim();
    this.searchTxt(keyword);
    this.setData({
      showAssociate: false,
    });
  },

  searchTxt(keyword) {
    if (keyword.length === 0) {
      wx.showModal({
        title: '提示',
        content: '搜索的内容不能为空',
        showCancel: false,
      });
      return;
    }
    this.setData({
      page: 1,
      keyword: keyword,
    });
    this.setHistory(keyword);
    this.getGoodsList();
  },

  searchSure() {
    let keyword = this.data.currVal.trim();
    this.searchTxt(keyword);
    this.setData({
      showAssociate: false,
    });
  },

  searchCancel() {
    wx.navigateBack({
      delta: 1,
    });
  },

  historyClick(e) {
    let keyword = e.currentTarget.dataset.value;
    if (keyword.length === 0) {
      return;
    }
    this.setData({
      page: 1,
      keyword: keyword,
      currVal: keyword,
    });
    this.getGoodsList();
  },

  getGoodsList() {
    let that = this;
    that.setData({
      show_history: false,
      show_result: true,
      page: 1,
      scroll_top: 0,
      goods_list: [],
      isloading: false,
    });
    let data = {};
    if (that.data.cat_id) {
      data.cat_id = that.data.cat_id;
      that.setActiveCat(data.cat_id);
    }
    if (that.data.keyword) {
      data.keyword = that.data.keyword;
    }
    data.limit = that.data.limit;
    that.showLoadingBar();
    that.is_loading = true;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.goods_search,
      data: data,
      success: res => {
        wx.hideLoading();
        if (res.code === 0) {
          if (res.data.list.length > 0) {
            that.setData({
              goods_list: res.data.list,
            });
          }
        }
        that.setData({
          isloading: true,
        });
      },
      complete: function() {
        that.hideLoadingBar();
        that.is_loading = false;
      },
    });
  },

  toDetails(e) {
    let { id, type, shopid = 0 } = e.currentTarget.dataset;
    app.ws_micro_shop_globalData.shopid = shopid;
    let url;
    if (type === 'default') {
      url = '/ws_micro_shop/pages/goods/goods?id=' + id;
    } else if (type === 'ms') {
      url = '/ws_micro_shop_ms/pages/miaosha/details/details?id=' + id;
    } else if (type === 'pt') {
      url = '/ws_micro_shop_pt/pages/pt/details/details?gid=' + id;
    } else {
      url = '/ws_micro_shop/pages/goods/goods?id' + id;
    }
    app.util.navigateTo(url, {}, false);
  },

  onListScrollBottom() {
    this.getMoreGoodsList();
  },

  getHistoryList(desc) {
    let is_desc = desc;
    is_desc = is_desc || false;
    let history_list = wx.getStorageSync('search_history_list');
    if (!history_list) {
      return [];
    }
    if (!is_desc) {
      return history_list;
    }
    return this.distinct(history_list);
  },

  distinct(arr) {
    if (!Array.isArray(arr)) {
      console.log('type error!');
      return;
    }
    let res = [];

    let obj = {};
    for (let i = 0; i < arr.length; i++) {
      if (!obj[arr[i].keyword]) {
        res.push(arr[i]);
        obj[arr[i].keyword] = 1;
      } else {
        obj[arr[i].keyword]++;
      }
    }
    return res;
  },

  setHistory(keyword) {
    let page = this;
    let history_list = page.getHistoryList(true);
    history_list.push({
      keyword: keyword,
    });
    for (let i in history_list) {
      if ({}.hasOwnProperty.call(history_list, i)) {
        if (history_list.length <= 20) {
          break;
        }
        history_list.splice(i, 1);
      }
    }
    wx.setStorageSync('search_history_list', history_list);
    page.setData({
      history_list,
    });
  },

  getMoreGoodsList() {
    let that = this;
    let data = {};
    if (that.data.cat_id) {
      data.cat_id = that.data.cat_id;
      that.setActiveCat(data.cat_id);
    }
    if (that.data.keyword) {
      data.keyword = that.data.keyword;
    }
    data.page = that.data.page || 1;
    that.showLoadingMoreBar();
    that.setData({
      is_loading: true,
    });
    that.setData({
      load_more_count: that.data.load_more_count + 1,
    });
    data.page = that.data.page + 1;
    data.limit = that.data.limit;
    that.setData({ page: data.page });
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.goods_search,
      data: data,
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let old_goods_list = that.data.goods_list;
          if (res.data.list.length > 0) {
            for (let i in res.data.list) {
              if ({}.hasOwnProperty.call(res.data.list, i)) {
                old_goods_list.push(res.data.list[i]);
              }
            }
            that.setData({
              goods_list: old_goods_list,
            });
          } else {
            that.setData({
              page: data.page - 1,
            });
          }
        }
      },
      complete: function() {
        that.setData({
          is_loading: false
        });
        // wx.showToast({
        //   title: '没有更多了',
        //   icon: 'none',
        // });
        that.hideLoadingMoreBar();
      },
    });
  },

  showLoadingBar() {
    this.setData({
      loading_class: 'active',
    });
  },

  hideLoadingBar() {
    this.setData({
      loading_class: '',
    });
  },

  showLoadingMoreBar() {
    this.setData({
      loading_more_active: 'active',
    });
  },

  hideLoadingMoreBar() {
    this.setData({
      loading_more_active: '',
    });
  },

  deleteSearchHistory() {
    this.setData({
      history_list: null,
    });
    wx.removeStorageSync('search_history_list');
  },

  loadHotSearchList() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.hotsearch,
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            hotsearch: res.data,
          });
        }
      },
    });
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  select(e) {
    let { index } = e.currentTarget.dataset;
    this.setData({
      isSelect: index,
    });
  },

  selectMore() {
    let animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    });
    this.animation = animation;
    this.animation.translateX(-303).step({ duration: 1000 });
    this.setData({
      animationData: this.animation.export(),
      flag: 1,
    });
  },

  hide() {
    let animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    });
    this.animation = animation;
    this.animation.translateX(0).step({ duration: 1000 });
    this.setData({
      animationData: this.animation.export(),
      flag: -1,
    });
  },
});
